package com.kele.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author kele
 * @date 2021/10/12 14:37
 * @description 使用原生的ThreadPool方式创建线程池
 */
public class ThreadPoolTest {

    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().availableProcessors());
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                /**
                 * 四种拒绝策略
                 * 1.AbortPolicy() 队列满了，还有线程请求进来，就不做处理，就抛出异常
                 * 2.CallerRunsPolicy()那来的回哪去
                 * 3.DiscardPolicy()队列满了就丢掉任务 不做处理
                 * 4.DiscardOldestPolicy()尝试跟第一个任务竞争，竞争成功就运行，不成功就丢掉，不抛出异常
                 */
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );

        try {
            for (int i = 1; i <=5; i++) {
                threadPoolExecutor.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"进来了");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }
    }
}
